// hooks/useAlarmFilter.js
import { ref, computed } from 'vue'

export default function useAlarmFilter(alarmsRef) {
    // 筛选状态
    const timeFilter = ref('') // 时间筛选，空字符串表示显示全部
    const locationFilter = ref('') // 位置筛选，空字符串表示显示全部
    const alarmTypeFilter = ref('') // 类型筛选，空字符串表示显示全部

    // 筛选选项
    const alarmTypes = computed(() => {
        // 使用 Set 去重后转为数组
        return [...new Set(alarmsRef.value.map(alarm => alarm.type))].filter(Boolean)
    })

    const locationOptions = computed(() => {
        // 使用 Set 去重后转为数组
        return [...new Set(alarmsRef.value.map(alarm => alarm.location))].filter(Boolean)
    })

    // 筛选逻辑
    const filterAlarms = (alarmsToFilter) => {
        let filtered = alarmsToFilter

        // 应用类型筛选
        if (alarmTypeFilter.value) {
            filtered = filtered.filter(alarm => alarm.type === alarmTypeFilter.value)
        }

        // 应用位置筛选
        if (locationFilter.value) {
            filtered = filtered.filter(alarm => alarm.location === locationFilter.value)
        }

        // 应用时间筛选
        if (timeFilter.value) {
            const now = new Date()
            let startDate = new Date()

            switch (timeFilter.value) {
                case 'today':
                    // 今天开始时间
                    startDate.setHours(0, 0, 0, 0)
                    break

                case 'yesterday':
                    // 昨天开始时间
                    startDate.setDate(startDate.getDate() - 1)
                    startDate.setHours(0, 0, 0, 0)
                    // 昨天结束时间
                    now.setDate(now.getDate() - 1)
                    now.setHours(23, 59, 59, 999)
                    break

                case 'last3days':
                    // 三天前
                    startDate.setDate(startDate.getDate() - 3)
                    startDate.setHours(0, 0, 0, 0)
                    break

                case 'lastWeek':
                    // 一周前
                    startDate.setDate(startDate.getDate() - 7)
                    startDate.setHours(0, 0, 0, 0)
                    break
            }

            const startTime = startDate.getTime()
            const endTime = now.getTime()

            filtered = filtered.filter(alarm => {
                const alarmTime = new Date(alarm.time).getTime()
                return alarmTime >= startTime && alarmTime <= endTime
            })
        }

        return filtered
    }

    return {
        // 筛选状态
        timeFilter,
        locationFilter,
        alarmTypeFilter,

        // 筛选选项
        alarmTypes,
        locationOptions,

        // 筛选方法
        filterAlarms
    }
}